import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import base from '@src/store/base'
import dayjs from "dayjs";
import { dumpFunc } from '@src/common/dump'
import { getPrototype } from '@src/api/shop'
import router from "@src/router";
import {
  payCouponSendQuery
} from "@src/api/coupon";
import {
  receiveBizCouponNew
} from "@src/api/coupon";
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: base,
      fields: ['themeColor', 'themeTitleColor']
    }
  ],
  properties: {
    btnType: {
      type: String,
      value: 'anniu'
    },
    modules: {
      type: Array,
      value: "",
    },
    login: {
      type: Boolean
    }
  },
  options: {
    multipleSlots: true,
    addGlobalClass: true
  },

  /**
   * 组件的初始数据
   */
  data: {
    featureList: [
      { title: '标题1', subTitle: '副标题1' }
    ],
    module: [],
    activeIndex: 0,
  },
  lifetimes: {
    attached: function () { if (this.data.modules.length > 0) { this.initData() } },
    moved: function () { },
    detached: function () { },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onLoad() { },
    initData() {
      let modules = this.data.modules[0];
      let module = JSON.parse(JSON.stringify(this.data.modules))
      this.setData({ module })
      this.handleFeatureList()
      //加载第一l列数据
      if (modules.biz && modules.biz.type === 'COUPON') {
        let biz = modules.biz;
        let params = JSON.parse(biz.params);
        if (params.couponIds.length > 0) { this.getCouponList(params.couponIds) }
      }
    },
    //feature宽度适配
    handleFeatureList() {
      let featureList = this.data.module;
      featureList.forEach(item => {
        if (item.title) {
          let len = item.title.length;
          console.log('len', len)
          if (len == 4) { item.width = '150rpx' }
          else if (len == 3) { item.width = '100rpx' }
          else if (len == 2) { item.width = '85rpx' }
          else { item.width = '100rpx' }
        }
      })
      this.setData({ module: featureList })
    },
    //批量查询券信息
    getCouponList(couponIds) {
      getPrototype(couponIds).then(res => {
        console.log(couponIds)
        let list = [];
        res.data.forEach(item => { list.push({ ...item.detail.prototype }) });
        this.setData({ couponList: this.initDate(list) });
        this.handleShakeCoupon()
      })
    },
    handleShakeCoupon() {
      let couponList = this.data.couponList;
      couponList.forEach(item => {
        item.ifloading = false;
        item.isClick = false;
      });
      this.setData({ couponList })
    },
    //判断是否需要跳webview
    handleWebview(couponType, id) {
      return new Promise((resolve, reject) => {
        if (couponType == 'cash_wx_pay') {
          payCouponSendQuery([id]).then(res => {
            if (res.code == 0) {
              if (res.data.needJump) {
                let urlParams = { url: res.data.webViewUrl }
                router.push({
                  name: 'mall/inside-url', params: urlParams,
                  events: {
                    webViewSuccess: (data) => {
                      resolve(true)
                    },
                  }
                });
              } else {
                resolve(true)
              }
            }
          })
        } else { resolve(true) }
      })
    },
    //领取券
    getCoupon(e) {
      if (!this.data.login) { this.triggerEvent('login'); return; }
      let receiveCode = e.currentTarget.dataset.item.receiveCode;
      let getCoupon = e.currentTarget.dataset.item.getCoupon;
      let id = e.currentTarget.dataset.item.id;
      let couponList = this.data.couponList;
      let prototype = e.currentTarget.dataset.item;
      let couponType = prototype.couponType;
      const self = this;
      this.handleWebview(couponType, id).then(res => {
        if (res) {
          console.log(self.data.couponList)
          let flag = true;
          let nowIndex = 0;
          self.setData({ id });
          if (!getCoupon) {
            couponList.forEach((item, index) => {
              if (item.id == id) {
                nowIndex = index
              }
            })
            let temp = 'couponList[' + nowIndex + '].ifloading'
            self.setData({ [temp]: true });
            receiveBizCouponNew(receiveCode).then(res => {
              if (res.code == 0) {
                let params = res.data.params;
                let codes = res.data.codes;
                if (codes) { self.setData({ code: codes[0] }) }
                if (res.data.finish) {
                  wx.showToast({
                    title: '领取成功',
                    icon: 'success',
                    duration: 2000
                  })
                  let couponArr = self.IfGetUtil(couponList, id);
                  if (codes) {
                    couponArr = self.setCodeFunc(couponList, codes[0], id);
                  }
                  self.setData({ couponList: couponArr, [temp]: false });
                } else {
                  let temp = 'couponList[' + nowIndex + '].ifloading'
                  self.setData({ [temp]: false })
                  self.showReceiveCoupon(prototype, params, codes)
                }
              }
            }).catch(error => {
              self.setData({ [temp]: false });
            })
          }
        }

      })


    },
    //工具函数,遍历 设置是否领取
    IfGetUtil(arr, id) {
      arr.forEach(item => { if (item.id === id) { item.getCoupon = true } })
      return arr
    },
    //工具函数，设置code值
    setCodeFunc(arr, code) {
      arr.forEach(item => { if (item.id === id) { item.code = code } })
      return arr;
    },
    //立即使用
    nowUseCoupon(e) {
      let code = e.currentTarget.dataset.item.code;
      if (code) {
        router.push({ name: 'member/couponDetailNew', params: { type: 1, model: 1, couponCode: code } })
      }
    },
    //init日期
    initDate(couponList) {
      if (couponList.length > 0) {
        couponList.forEach((item,index) => {
          item.endTime = dayjs(item.endTime).format('YYYY-MM-DD')
          const fale = dayjs().isBefore(dayjs(item.endTime))
          if(!fale){
            item.overdue = true
          }
        });
        return couponList
      }
    },
    getIndexList(e) {
      if (!this.data.login) { this.triggerEvent('login'); return; }
      let id = e.currentTarget.dataset.id;
      let modules = this.data.modules;
      let temp = null;
      modules.forEach((item, index) => {
        if (item.id == id) {
          let biz = item.biz;
          this.setData({ activeIndex: index })
          if (biz && biz.type === 'COUPON') {
            temp = JSON.parse(biz.params);
          }
        }
      })
      if (temp.couponIds.length > 0) { this.getCouponList(temp.couponIds) }
    },
    //展示领取弹框
    showReceiveCoupon(prototype, params, codes) {
      this.selectComponent("#receiveCoupon").dialogShow(prototype, params, codes);
    },
    //监听微信商家券是否领取成功
    getNowFunc() {
      // let couponList = this.data.couponList;
      // let showList = this.data.showList;
      const self = this;
      let id = this.data.id;
      let code = this.data.code;
      let couponList = self.IfGetUtil(this.data.couponList, id);
      couponList = self.setCodeFunc(couponList, code);
      this.setData({ couponList: couponList })
    },
  }
})
